<template>
  <div class="industry-container">
    <div class="industry-header">
      <h2>行业类别管理</h2>
      <p class="subtitle">管理企业的行业分类信息</p>
    </div>
    
    <div class="industry-content">
      <!-- 上部分：表单和提示 -->
      <div class="form-container">
        <div class="form-left">
          <el-form 
            ref="industryFormRef"
            :model="industryForm" 
            :rules="formRules"
            label-width="80px"
            class="industry-form"
          >
            <el-form-item label="行业名称" prop="name">
              <el-input 
                v-model="industryForm.name" 
                placeholder="请输入行业名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="排序" prop="sort">
              <el-input-number 
                v-model="industryForm.sort" 
                :min="0" 
                :max="999"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
          
          <div class="form-actions">
            <el-button @click="clearForm" plain>
              <el-icon><Refresh /></el-icon>
              清空
            </el-button>
            <el-button type="primary" @click="createIndustry" :disabled="!canCreate">
              <el-icon><Plus /></el-icon>
              创建
            </el-button>
            <el-button type="success" @click="updateIndustry" :disabled="!selectedNode">
              <el-icon><Edit /></el-icon>
              更新
            </el-button>
            <el-button type="danger" @click="deleteIndustry" :disabled="!selectedNode">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
        
        <div class="form-right">
          <div class="tips-section">
            <el-alert
              :title="getTipsTitle()"
              type="info"
              :closable="false"
              show-icon
            >
              <div class="tips-content">
                <p>1、【创建】为新增行业，未选中行业则创建顶级分类，选中则创建该节点下子分类，最后一级分类不可创建；</p>
                <p>2、【更新】前需要点击任何一项行业，在表单中修改后点击【更新】即可提交修改；</p>
                <p>3、【删除】前需要选中任何一项行业后，方可点击删除；</p>
                <p>4、【清空】清除表单中的待提交信息。</p>
              </div>
            </el-alert>
          </div>
        </div>
      </div>
      
      <!-- 下部分：树形结构 -->
      <div class="tree-container">
        <div class="tree-header">
          <h3>行业结构</h3>
          <div class="tree-actions">
            <el-button type="primary" text @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="warning" text @click="handleRefreshCache">
              <el-icon><Refresh /></el-icon>
              刷新缓存
            </el-button>
          </div>
        </div>
        
        <el-tree
          v-loading="loading"
          ref="industryTreeRef"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="false"
          :load="loadNode"
          lazy
          node-key="id"
          highlight-current
          @node-click="handleNodeClick"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
          class="industry-tree"
          :empty-text="treeData.length === 0 ? '暂无数据' : '加载中...'"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <el-icon class="node-icon">
                <Folder v-if="!data.isLeaf" />
                <Document v-else />
              </el-icon>
              <span class="node-label">{{ data.name }}</span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh, Folder, Document } from '@element-plus/icons-vue'
import { getTopList, getChildrenList, addIndustry, updateIndustry as apiUpdateIndustry, deleteIndustry as apiDeleteIndustry, refreshCache } from '@/api/industry'

// 表单相关
const industryFormRef = ref()
const industryForm = ref({
  name: '',
  sort: 0
})

const formRules = {
  name: [
    { required: true, message: '请输入行业名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 树形结构相关
const industryTreeRef = ref()
const treeData = ref([])
const selectedNode = ref(null)
const expandedNodes = ref(new Set())
const childrenCache = ref(new Map())
const loading = ref(false)

const treeProps = {
  children: 'children',
  label: 'name',
  isLeaf: 'isLeaf',
  hasChildren: 'hasChildren'
}

// 计算属性
const canCreate = computed(() => {
  if (!selectedNode.value) return true // 可以创建顶级分类
  return selectedNode.value.level < 2 // 只有两级，第二级不能创建子分类
})

// 获取提示标题
const getTipsTitle = () => {
  if (!selectedNode.value) {
    return '当前未选中任何节点'
  }
  return `当前选中的节点为: ${selectedNode.value.name}`
}

// 加载一级行业数据
const loadTopLevelIndustries = async () => {
 loading.value = true
  try {
    const data = await getTopList()
    treeData.value = data.map(item => ({
      ...item,
      level: 1,
      hasChildren: true // 标记有子节点，用于懒加载
    }))
  } catch (error) {
    ElMessage.error('加载行业数据失败')
    console.error('加载行业数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载子行业数据
const loadChildrenIndustries = async (parentId) => {
  if (childrenCache.value.has(parentId)) {
    return childrenCache.value.get(parentId)
  }
  
  try {
    const data = await getChildrenList(parentId)
    const children = data.map(item => ({
      ...item,
      level: 2,
      isLeaf: true // 二级分类都是叶子节点
    }))
    childrenCache.value.set(parentId, children)
    return children
  } catch (error) {
    ElMessage.error('加载子行业数据失败')
    console.error('加载子行业数据失败:', error)
    return []
  }
}

// 处理节点点击
const handleNodeClick = (data, node) => {
  selectedNode.value = data
  industryForm.value = {
    name: data.name,
    sort: data.sort
  }
}

// 懒加载节点数据
const loadNode = async (node, resolve) => {
  try {
    if (node.level === 0) {
      // 根节点，加载一级行业
      const data = await getTopList()
      const nodes = data.map(item => ({
        ...item,
        level: 1,
        hasChildren: true // 标记有子节点
      }))
      resolve(nodes)
    } else if (node.level === 1) {
      // 一级节点，加载子行业
      const data = await getChildrenList(node.data.id)
      const children = data.map(item => ({
        ...item,
        level: 2,
        isLeaf: true // 二级节点是叶子节点
      }))
      resolve(children)
    } else {
      resolve([])
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
    resolve([])
  }
}

// 处理节点收起
const handleNodeCollapse = (data) => {
  expandedNodes.value.delete(data.id)
}

// 清空表单
const clearForm = () => {
  industryForm.value = {
    name: '',
    sort: 0
  }
  selectedNode.value = null
  industryTreeRef.value?.setCurrentKey(null)
}

// 创建行业
const createIndustry = async () => {
  if (!industryFormRef.value) return
  
  await industryFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          name: industryForm.value.name,
          sort: industryForm.value.sort,
          fatherId: selectedNode.value ? selectedNode.value.id : '0',
          isLeaf: selectedNode.value ? true : false,
          level: selectedNode.value ? 2 : 1
        }
        
        await addIndustry(params)
        ElMessage.success('创建成功')
        clearForm()
        refreshData()
      } catch (error) {
        ElMessage.error('创建失败')
        console.error('创建行业失败:', error)
      }
    }
  })
}

// 更新行业
const updateIndustry = async () => {
  if (!selectedNode.value || !industryFormRef.value) return
  
  await industryFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          id: selectedNode.value.id,
          name: industryForm.value.name,
          sort: industryForm.value.sort
        }
        
        await apiUpdateIndustry(params)
        ElMessage.success('更新成功')
        refreshData()
      } catch (error) {
        ElMessage.error('更新失败')
        console.error('更新行业失败:', error)
      }
    }
  })
}

// 删除行业
const deleteIndustry = async () => {
  if (!selectedNode.value) return
  
  const isTopLevel = selectedNode.value.level === 1
  const confirmMessage = isTopLevel 
    ? `确定要删除行业 "${selectedNode.value.name}" 吗？此操作将同步删除其下的所有二级行业。`
    : `确定要删除行业 "${selectedNode.value.name}" 吗？`
  
  try {
    await ElMessageBox.confirm(
      confirmMessage,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await apiDeleteIndustry(selectedNode.value.id)
    ElMessage.success('删除成功')
    clearForm()
    refreshData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除行业失败:', error)
    }
  }
}

// 刷新数据
const refreshData = async () => {
  // 使用懒加载模式，重新加载根节点数据
  if (industryTreeRef.value) {
    // 清空当前选中的节点
    selectedNode.value = null
    industryTreeRef.value?.setCurrentKey(null)
    
    // 重新加载根节点
    industryTreeRef.value.root.loaded = false
    industryTreeRef.value.root.loadData()
    
    ElMessage.success('数据已刷新')
  }
}

// 刷新系统缓存
const handleRefreshCache = async () => {
  try {
    await ElMessageBox.confirm(
      '系统缓存将在明天凌晨3:00自动刷新，确定要立即执行刷新操作吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await refreshCache()
    ElMessage.success('缓存刷新请求已提交，系统将在明天凌晨3:00完成刷新')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('刷新缓存失败')
      console.error('刷新缓存失败:', error)
    }
  }
}

// 初始化
onMounted(() => {
  // 懒加载模式下，树形组件会自动加载根节点数据
})
</script>

<style scoped lang="scss">
.industry-container {
  padding: 16px;
  background: #ffffff;
  min-height: 100%;
}

.industry-header {
  margin-bottom: 16px;
  
  h2 {
    margin: 0 0 4px 0;
    color: #111827;
    font-size: 20px;
    font-weight: 600;
  }
  
  .subtitle {
    margin: 0;
    color: #6b7280;
    font-size: 14px;
  }
}

.industry-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 上部分：表单和提示 */
.form-container {
  display: flex;
  gap: 24px;
  align-items: flex-start;
  
  .form-left {
    flex: 1;
    max-width: 500px;
  }
  
  .form-right {
    flex: 1;
    min-width: 300px;
  }
}

.industry-form {
  margin-bottom: 16px;
}

.form-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  
  .el-button {
    flex: 1;
  }
}

.tips-section {
  .el-alert {
    margin-bottom: 0;
  }
  
  .tips-content {
    margin-top: 8px;
    
    p {
      margin: 4px 0;
      font-size: 13px;
      line-height: 1.6;
      color: #606266;
    }
  }
}

/* 下部分：树形结构 */
.tree-container {
  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    h3 {
      margin: 0;
      color: #111827;
      font-size: 16px;
      font-weight: 500;
    }
    
    .tree-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
  
  .node-icon {
    color: #409eff;
  }
  
  .node-label {
    flex: 1;
    font-size: 14px;
  }
  
  
}

.industry-tree {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 8px 0;
  
  .el-tree-node {
    &.is-current > .el-tree-node__content {
      background-color: #f3f4f6;
    }
    
    .el-tree-node__content {
      height: 36px;
      padding: 0 12px;
      transition: background-color 0.2s;
      
      &:hover {
        background-color: #f9fafb;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .form-container {
    flex-direction: column;
    gap: 16px;
  }
  
  .form-left,
  .form-right {
    max-width: none;
    min-width: auto;
  }
  
  .form-actions {
    flex-direction: column;
    
    .el-button {
      margin: 2px 0;
    }
  }
}
</style>